<?php

namespace App\Admin\Forms\Config;

use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use App\Models\Config as Model;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Cash extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         $input['cash_dates'] = request()->input("cash_dates");
         $res = 0;
         if ($input){
             try {
                 foreach ($input as $key=>$value){
                     $model = Model::where('name',$key)->first();
                     $model->value = is_array($value)?json_encode($value):$value;
                     $res += $model->save();
                 }
             }catch (ModelNotFoundException|Exception $e){
                 return $this->response()->error($e->getMessage())->refresh();
             }
         }
         return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }


    protected function getCashTimesOptions(): array
    {
        $days = [31,28,31,30,31,30,31,31,30,31,30,31];
        $year = date("Y");
        if ($year % 4 == 0 && $year % 100 != 0  || $year % 400 == 0){
            $days[1] = 29;
        }else{
            $days[1] = 28;
        }
        $options = [];
        foreach ($days as $key=>$day){
            $month = $key+1<10?"0".($key+1):$key+1;
            $d = ['label'=>$month."月",'value'=>$month];
            for ($i=1;$i<=$day;$i++){
                $h = $i<10?"0".$i:$i;
                $d['children'][] = ['label'=>$h."号",'value'=>$month."-".$h];
            }
            $options[] = $d;
        }
        return $options;
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        Admin::requireAssets('@vue');
        Admin::requireAssets('@naive-ui');
        $cash_dates = $this->getDefault()['cash_dates'];
        if ($cash_dates){
            $cash_dates = explode(",",$cash_dates);
        }
        $this->html(view('admin.rule.cash',['options'=>$this->getCashTimesOptions(),'cash_dates'=>$cash_dates]),"提现时间段");
        $this->rate("cash_rate","提现手续费率");
        $this->ckeditor("cash_rule","提现手续费规则");
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return $this->getDefault();
    }

    protected function getDefault(){
        return Model::query()->pluck("value","name")->toArray();
    }
}
